package com.zh.common.view.web

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.http.SslError
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View.OnLongClickListener
import android.webkit.SslErrorHandler
import android.webkit.URLUtil
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ProgressBar
import androidx.core.widget.NestedScrollView
import com.blankj.utilcode.util.LogUtils
import com.zh.common.BuildConfig
import com.zh.common.listener.OnSelectListener

/**
 * WebView默认设置一些属性
 * 1、如果有播放视频，所在的Activity必须设置以下属性
 * android:configChanges="orientation|screenSize|keyboardHidden"
 * android:launchMode="singleTask"
 * android:theme="@style/Theme.AppCompat.Light.NoActionBar"
 * android:windowSoftInputMode="stateVisible|adjustResize"
 * 2、Scrollview嵌入WebView，解决在WebView中点击链接页面会向上滑动一下
 * android:descendantFocusability="blocksDescendants"
 */
class IWebView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : WebView(context, attrs) {

    private val TAG = "IWebView"
    private var touchX = 0
    private var touchY = 0
    private var mOnSelectListener: OnSelectListener? = null
    private val iWebChromeClient by lazy {
        object : IWebChromeClient(this, { webpageName = it }, { webpageIcon = it }) {}
    }
    private val iWebViewClient by lazy {
        object : IWebViewClient(this, { onIMeasure() }) {}
    }
    var mScrollView: NestedScrollView? = null
    var webpageName: String? = null
    var webpageIcon: String? = null
    var activity: Activity? = null
        set(value) {
            if (field != value) {
                field = value
                iWebChromeClient.activity = value
            }
        }
    var progress: ProgressBar? = null
        set(value) {
            if (field != value) {
                field = value
                iWebChromeClient.progress = value
            }
        }

    init {
        /**
         * 谷歌浏览器调试Webview的地址，需要翻墙
         * chrome://inspect/#devices
         */
        setWebContentsDebuggingEnabled(BuildConfig.DEBUG) // 主要是执行这一行，参数传 true
        initSettings
        setOnLongClickListener()
    }

    //设置webView属性
    private val initSettings: Unit
        get() {
            //扩大比例的缩放
            settings.apply {
                useWideViewPort = true
                // 设置可以支持缩放
                setSupportZoom(false)
                builtInZoomControls = true
                // 这个解决跨域的问题 - 不安全
                allowFileAccess = true
                //自适应屏幕
                loadWithOverviewMode = true
                //支持javascript
                javaScriptEnabled = true
                //支持通过JS打开新窗口
                javaScriptCanOpenWindowsAutomatically = true
                //关闭缓存
                cacheMode = WebSettings.LOAD_DEFAULT
                //支持内容重新布局
                layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
                //处理视频问题
                pluginState = WebSettings.PluginState.ON
                mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
                domStorageEnabled = true
                databaseEnabled = true
            }
            webViewClient = iWebViewClient
            webChromeClient = iWebChromeClient
        }

    fun needRequestedOrientation(orientation: Int) {
        LogUtils.e("needRequestedOrientation: $orientation")
        activity?.requestedOrientation = orientation
    }

    private fun onIMeasure() {
        if (mScrollView == null) return
        //webView加载完成之后重新测量webView的高度
        val params = layoutParams
        params.width = resources.displayMetrics.widthPixels
        params.height = height - mScrollView!!.height
        layoutParams = params
    }

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        touchX = event.rawX.toInt()
        touchY = event.rawY.toInt()
        return super.onInterceptTouchEvent(event)
    }

    private fun setOnLongClickListener() {
        setOnLongClickListener(OnLongClickListener {
            val result = hitTestResult ?: return@OnLongClickListener false
            when (result.type) {
                HitTestResult.EDIT_TEXT_TYPE -> { // 选中的文字类型

                }

                HitTestResult.PHONE_TYPE -> { // 处理拨号

                }

                HitTestResult.EMAIL_TYPE -> {// 处理Email

                }

                HitTestResult.GEO_TYPE -> {// 　地图类型

                }

                HitTestResult.SRC_ANCHOR_TYPE -> {  // 超链接

                }

                HitTestResult.SRC_IMAGE_ANCHOR_TYPE, HitTestResult.IMAGE_TYPE -> {
                    // 带有链接的图片类型 - 处理长按图片的菜单项
                    val url = result.extra
                    if (mOnSelectListener != null && url != null && URLUtil.isValidUrl(url)) {
                        mOnSelectListener?.onSelected(touchX, touchY, result.type, url)
                    }
                    return@OnLongClickListener true
                }

                HitTestResult.UNKNOWN_TYPE -> { //未知

                }
            }
            false
        })
    }

    fun setOnSelectListener(listener: OnSelectListener) {
        mOnSelectListener = listener
    }

    interface MyWebViewClient {
        fun onPageFinished(view: WebView, url: String)
        fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?)
        fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean
        fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError)
    }

    fun setMyWebViewClient(mMyWebViewClient: MyWebViewClient) {
        iWebViewClient.mMyWebViewClient = mMyWebViewClient
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        iWebChromeClient.onActivityResult(requestCode, resultCode, data)
    }
}